#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
企业舆情分析系统 - Web服务器启动脚本
便捷启动脚本，用于启动Web服务器和初始化系统
"""

import os
import sys
import json
import subprocess
import time
from pathlib import Path

def check_dependencies():
    """检查必要的依赖包"""
    print("🔍 检查系统依赖...")
    
    required_packages = [
        'flask', 'flask_cors', 'aiohttp', 'sqlite3', 
        'pandas', 'numpy', 'colorama'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            if package == 'sqlite3':
                import sqlite3
            elif package == 'flask_cors':
                import flask_cors
            else:
                __import__(package)
            print(f"✅ {package} - 已安装")
        except ImportError:
            print(f"❌ {package} - 未安装")
            missing_packages.append(package)
    
    if missing_packages:
        print(f"\n⚠️ 缺少以下依赖包: {', '.join(missing_packages)}")
        print("📦 正在自动安装...")
        
        # 自动安装缺失的包
        for package in missing_packages:
            try:
                if package == 'flask_cors':
                    subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'Flask-CORS'])
                else:
                    subprocess.check_call([sys.executable, '-m', 'pip', 'install', package])
                print(f"✅ {package} 安装成功")
            except subprocess.CalledProcessError:
                print(f"❌ {package} 安装失败，请手动安装")
                return False
    
    return True

def check_project_structure():
    """检查项目结构"""
    print("\n🏗️ 检查项目结构...")
    
    required_files = [
        'backend_api.py',
        'enterprise_analysis_system.py',
        'threat_analysis_system.py',
        'multi_ai_chat.py',
        'question_generator.py',
        'database_init.py',
        'web/index.html',
        'web/js/app.js'
    ]
    
    missing_files = []
    
    for file_path in required_files:
        if os.path.exists(file_path):
            print(f"✅ {file_path}")
        else:
            print(f"❌ {file_path} - 文件不存在")
            missing_files.append(file_path)
    
    if missing_files:
        print(f"\n⚠️ 缺少以下文件: {', '.join(missing_files)}")
        return False
    
    return True

def create_default_config():
    """创建默认配置文件"""
    print("\n⚙️ 创建默认配置文件...")
    
    try:
        # 创建API Keys配置文件
        api_keys_file = "api_keys.json"
        if not os.path.exists(api_keys_file):
            default_config = {
                "baidu": {"api_key": "", "secret_key": "", "enabled": False},
                "aliyun": {"api_key": "", "enabled": False},
                "zhipu": {"api_key": "", "enabled": False},
                "kimi": {"api_key": "", "enabled": False},
                "deepseek": {"api_key": "", "enabled": False}
            }
            
            with open(api_keys_file, 'w', encoding='utf-8') as f:
                json.dump(default_config, f, ensure_ascii=False, indent=2)
            
            print(f"✅ 创建 {api_keys_file}")
        else:
            print(f"✅ {api_keys_file} 已存在")
        
        return True
        
    except Exception as e:
        print(f"❌ 配置文件创建失败: {e}")
        return False

def check_database():
    """检查数据库状态并自动修复"""
    print("\n🗄️ 检查数据库状态...")
    
    db_file = "enterprise_analysis.db"
    needs_init = False
    
    if os.path.exists(db_file):
        # 检查数据库文件大小
        file_size = os.path.getsize(db_file)
        if file_size == 0:
            print("⚠️ 数据库文件为空，需要初始化")
            needs_init = True
        else:
            try:
                import sqlite3
                conn = sqlite3.connect(db_file)
                cursor = conn.cursor()
                
                # 检查主要表是否存在
                cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
                tables = [row[0] for row in cursor.fetchall()]
                
                required_tables = [
                    'enterprises', 'analysis_sessions', 'questions', 
                    'ai_responses', 'threat_analysis', 'threat_analysis_sessions',
                    'threat_statistics', 'system_config', 'audit_log'
                ]
                
                missing_tables = [table for table in required_tables if table not in tables]
                
                if missing_tables:
                    print(f"⚠️ 数据库缺少表: {', '.join(missing_tables)}")
                    needs_init = True
                else:
                    print("✅ 数据库结构完整")
                
                conn.close()
            except Exception as e:
                print(f"❌ 数据库检查失败: {e}")
                needs_init = True
    else:
        print("⚠️ 数据库文件不存在")
        needs_init = True
    
    # 如果需要初始化，执行数据库修复
    if needs_init:
        print("🔧 正在初始化/修复数据库...")
        try:
            from database_init import DatabaseInitializer
            
            db_init = DatabaseInitializer(db_file)
            db_init.init_all_tables(recreate=True)
            
            print("✅ 数据库初始化/修复成功")
            
            # 验证修复结果
            import sqlite3
            conn = sqlite3.connect(db_file)
            cursor = conn.cursor()
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
            tables = cursor.fetchall()
            conn.close()
            
            print(f"📊 数据库包含 {len(tables)} 个表")
            
        except Exception as e:
            print(f"❌ 数据库初始化/修复失败: {e}")
            import traceback
            traceback.print_exc()
            return False
    
    return True

def start_web_server():
    """启动Web服务器"""
    print("\n🚀 启动企业舆情分析系统...")
    
    try:
        # 导入并启动Flask应用
        from backend_api import app
        
        print("=" * 60)
        print("🌟 企业舆情分析系统 - Web服务器")
        print("=" * 60)
        print("📱 Web界面: http://localhost:5000")
        print("🔗 API接口: http://localhost:5000/api/health")
        print("⚙️ 配置管理: http://localhost:5000/#config")
        print("📊 数据大屏: http://localhost:5000/#dashboard")
        print("=" * 60)
        print("💡 提示: 首次使用请先在'系统配置'中配置AI服务API Key")
        print("📖 使用说明:")
        print("   1. 配置AI服务API Key")
        print("   2. 数据库已自动初始化")
        print("   3. 开始企业分析")
        print("   4. 查看分析结果和威胁评估")
        print("=" * 60)
        print("✅ 数据库修复功能已集成，启动时自动检查和修复")
        print("🔄 按 Ctrl+C 停止服务器")
        print("=" * 60)
        
        # 启动Flask应用
        app.run(host='0.0.0.0', port=5000, debug=True, threaded=True)
        
    except ImportError as e:
        print(f"❌ 导入模块失败: {e}")
        print("请确保所有Python文件都在正确位置")
        return False
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        return False

def main():
    """主函数"""
    print("🎯 企业舆情分析系统 - 启动检查")
    print("=" * 50)
    
    # 检查步骤
    checks = [
        ("检查依赖包", check_dependencies),
        ("检查项目结构", check_project_structure),
        ("创建配置文件", create_default_config),
        ("检查数据库", check_database)
    ]
    
    for check_name, check_func in checks:
        print(f"\n{check_name}...")
        try:
            if not check_func():
                print(f"❌ {check_name}失败，请检查后重试")
                return False
        except Exception as e:
            print(f"❌ {check_name}出错: {e}")
            return False
    
    print("\n✅ 所有检查完成，准备启动服务器...")
    time.sleep(1)
    
    # 启动Web服务器
    start_web_server()

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n👋 企业舆情分析系统已停止")
    except Exception as e:
        print(f"\n❌ 系统启动失败: {e}")
        sys.exit(1) 